package com.expert.miniapp.service.impl;

import com.expert.miniapp.config.AISummaryConfigProperties;
import com.expert.miniapp.dao.Demand;
import com.expert.miniapp.service.AIDemandSummaryService;
import com.expert.miniapp.util.DifyClient;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * AIDemandSummaryServiceImpl - AI需求摘要生成服务实现（Dify格式）
 *
 * 调用Dify Summary AI端点生成需求摘要
 * 使用指数退避重试策略（1s, 2s, 4s）
 * 使用blocking（非流式）模式
 *
 * @author System
 * @since 2025-11-11
 * @updated 2025-11-14 迁移到Dify API格式
 */
@Service
public class AIDemandSummaryServiceImpl implements AIDemandSummaryService {

    private static final Logger logger = LoggerFactory.getLogger(AIDemandSummaryServiceImpl.class);

    @Autowired
    private AISummaryConfigProperties aiSummaryConfig;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public String generateDemandSummary(Demand demand) {
        logger.info("开始生成需求摘要: demandId={}", demand.getDemandId());

        int maxRetries = Optional.ofNullable(aiSummaryConfig.getMaxRetries()).orElse(3);
        int baseRetryDelay = Optional.ofNullable(aiSummaryConfig.getRetryDelay()).orElse(1000);

        RuntimeException lastException = null;

        // 重试循环：maxRetries次重试 + 1次初始尝试
        for (int attempt = 0; attempt <= maxRetries; attempt++) {
            try {
                if (attempt > 0) {
                    // 指数退避：2^attempt * baseRetryDelay = 1s, 2s, 4s
                    long delay = (long) Math.pow(2, attempt - 1) * baseRetryDelay;
                    logger.info("重试生成摘要: 第{}次尝试 (延迟{}ms)", attempt + 1, delay);
                    Thread.sleep(delay);
                }

                String summary = callAISummaryAPI(demand);

                logger.info("摘要生成成功: demandId={}, 长度={}", demand.getDemandId(), summary.length());
                return summary;

            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException("摘要生成被中断", e);

            } catch (RuntimeException e) {
                logger.warn("摘要生成失败 (尝试{}/{}): {}", attempt + 1, maxRetries + 1, e.getMessage());
                lastException = e;

                // 如果是最后一次尝试，不再重试
                if (attempt == maxRetries) {
                    break;
                }
            }
        }

        // 所有重试都失败
        logger.error("摘要生成失败，已达最大重试次数: demandId={}", demand.getDemandId());
        throw new RuntimeException("AI摘要生成失败: " + lastException.getMessage(), lastException);
    }

    /**
     * 调用AI API生成摘要（OpenAI格式，/chat/completions端点）
     */
    private String callAISummaryAPI(Demand demand) {
        // 1. 构建inputs（需求字段作为content对象）
        Map<String, Object> content = buildDemandInputs(demand);
        logger.debug("AI摘要content: {}", content);

        // 2. 调用OpenAI格式API
        try {
            logger.info("调用AI摘要接口（OpenAI格式）: url={}, model={}",
                    aiSummaryConfig.getUrl(), aiSummaryConfig.getModel());

            String response = DifyClient.callOpenAIFormat(
                    aiSummaryConfig.getUrl(),
                    aiSummaryConfig.getKey(),
                    content,                        // 作为message.content对象
                    aiSummaryConfig.getModel(),     // gpt-4o-mini
                    false,                          // stream=false
                    aiSummaryConfig.getTimeout()
            );

            if (response == null || response.trim().isEmpty()) {
                throw new RuntimeException("AI返回内容为空");
            }

            logger.info("AI摘要返回成功，长度: {}", response.length());

            // 3. 清理和验证摘要
            return cleanSummary(response);

        } catch (Exception e) {
            logger.error("AI摘要调用失败: {}", e.getMessage());
            throw new RuntimeException("AI API调用失败: " + e.getMessage(), e);
        }
    }

    /**
     * 构建Dify inputs对象（仅包含有值的字段）
     */
    private Map<String, Object> buildDemandInputs(Demand demand) {
        Map<String, Object> inputs = new LinkedHashMap<>();

        if (hasText(demand.getDemandName())) {
            inputs.put("需求名称", demand.getDemandName());
        }

        if (hasText(demand.getResearchObjective())) {
            inputs.put("研究目标", demand.getResearchObjective());
        }

        if (hasText(demand.getTechnologyField())) {
            inputs.put("技术领域", demand.getTechnologyField());
        }

        if (hasText(demand.getCoreTechnicalChallenges())) {
            inputs.put("核心技术挑战", demand.getCoreTechnicalChallenges());
        }

        if (hasText(demand.getApplicationScenario())) {
            inputs.put("应用场景", demand.getApplicationScenario());
        }

        if (hasText(demand.getExpectedOutcomes())) {
            inputs.put("预期成果", demand.getExpectedOutcomes());
        }

        return inputs;
    }

    /**
     * 清理和验证摘要内容
     */
    private String cleanSummary(String summary) {
        if (summary == null) {
            return "";
        }

        // 去除首尾空白
        summary = summary.trim();

        // 去除常见的前缀/后缀
        summary = summary.replaceAll("^(摘要：|Summary:|需求摘要：|以下是摘要：)", "");
        summary = summary.replaceAll("(。*$)", "。");

        // 去除多余的换行（替换为空格）
        summary = summary.replaceAll("\n+", " ");

        // 去除多余的空格
        summary = summary.replaceAll("\\s+", " ");

        return summary.trim();
    }

    /**
     * 检查文本是否有效
     */
    private boolean hasText(String text) {
        return text != null && !text.trim().isEmpty() && !"None".equalsIgnoreCase(text.trim());
    }
}
